<template>
  <el-dialog
    v-model="dialogVisible"
    title="搜索群聊"
    width="500px"
  >
    <div class="search-container">
      <el-input
        v-model="keyword"
        placeholder="请输入群名称关键词"
        clearable
        @keyup.enter="searchGroups"
      >
        <template #append>
          <el-button @click="searchGroups" :loading="searching">
            <el-icon><EpSearch /></el-icon>搜索
          </el-button>
        </template>
      </el-input>
      
      <div class="search-results margin_t-20">
        <div v-if="searching" class="loading-container flex_j_c-center">
          <el-icon class="is-loading" :size="24"><EpLoading /></el-icon>
        </div>
        <div v-else-if="searched && results.length === 0" class="empty-tip flex_j_c-center">
          未找到相关群聊
        </div>
        <div v-else-if="results.length > 0" class="result-list">
          <div 
            v-for="group in results" 
            :key="group.id" 
            class="result-item flex_a_i-center flex_j_c-space-between"
          >
            <div class="flex_a_i-center">
              <el-avatar :src="group.avatar || defaultAvatar" :size="40"></el-avatar>
              <div class="info margin_l-10">
                <div class="name">{{ group.name }}</div>
                <div class="desc text-color-secondary font-size-12">
                  {{ group.memberCount }}人 | {{ group.description || '暂无描述' }}
                </div>
              </div>
            </div>
            <el-button 
              type="primary" 
              size="small" 
              :loading="joining === group.id"
              :disabled="group.joined || group.applying"
              @click="joinGroup(group)"
            >
              {{ group.joined ? '已加入' : (group.applying ? '申请中' : '申请加入') }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoomStore } from '@/stores'
import { Search as EpSearch, Loading as EpLoading } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'join'])

// 对话框可见性
const dialogVisible = ref(props.modelValue)

// 搜索相关
const keyword = ref('')
const searching = ref(false)
const searched = ref(false)
const results = ref([])
const joining = ref(null)
const defaultAvatar = '/src/assets/images/group.png'

// 获取room store
const roomStore = useRoomStore()

// 同步对话框可见性
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
})

watch(() => dialogVisible.value, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    // 关闭对话框时重置状态
    keyword.value = ''
    results.value = []
    searched.value = false
  }
})

// 搜索群聊
const searchGroups = async () => {
  if (!keyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  searching.value = true
  try {
    const response = await roomStore.searchGroups({
      keyword: keyword.value.trim()
    })
    
    if (response) {
      results.value = response.map(group => ({
        ...group,
        joined: group.joined || false,
        applying: group.applying || false
      }))
    } else {
      results.value = []
    }
    searched.value = true
  } catch (error) {
    console.error('搜索群聊失败:', error)
    ElMessage.error('搜索群聊失败')
    results.value = []
  } finally {
    searching.value = false
  }
}

// 申请加入群聊
const joinGroup = async (group) => {
  joining.value = group.id
  try {
    const success = await roomStore.joinGroup(group.id)
    if (success) {
      group.applying = true
      ElMessage.success(`已发送加入申请，请等待群主审核`)
      emit('join', { ...group, status: 'applying' })
    }
  } catch (error) {
    console.error('申请加入群聊失败:', error)
    ElMessage.error('申请加入群聊失败')
  } finally {
    joining.value = null
  }
}
</script>

<style lang="scss" scoped>
.search-container {
  .loading-container, .empty-tip {
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--el-text-color-secondary);
  }
  
  .result-list {
    max-height: 400px;
    overflow-y: auto;
    
    .result-item {
      padding: 10px;
      border-radius: 4px;
      
      &:hover {
        background-color: var(--el-fill-color-light);
      }
      
      .info {
        flex: 1;
        
        .name {
          font-weight: 500;
          margin-bottom: 3px;
        }
        
        .desc {
          color: var(--el-text-color-secondary);
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 300px;
        }
      }
      
      & + .result-item {
        margin-top: 5px;
        border-top: 1px solid var(--el-border-color-lighter);
      }
    }
  }
}
</style> 